package com.eorchis.module.interioruser.ui.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.commond.converter.IQueryCommondAttributeConverter;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.classuser.domain.QueryClassUserBean;
import com.eorchis.module.exceluitls.ReadExcelUtils;
import com.eorchis.module.exceluitls.domain.excel.ExcelSheet;
import com.eorchis.module.interioruser.domain.InteriorUserQueryBean;
import com.eorchis.module.interioruser.service.IInteriorUserService;
import com.eorchis.module.interioruser.ui.commond.InteriorUserQueryCommond;
import com.eorchis.module.interioruser.ui.commond.InteriorUserValidCommond;
import com.eorchis.module.security.cas.domain.Role;
import com.eorchis.module.util.Base64Util;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: InteriorUserController<br>
 * Description: 内部用户管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Administrator
 * @createDate 2015-01-04
 * @version $Revision$
 */
@Controller("interiorUserController")
@RequestMapping(value = InteriorUserController.MODULE_PATH)
public class InteriorUserController extends AbstractBaseController<InteriorUserValidCommond,InteriorUserQueryCommond> {
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/interioruser";
	// 内部用户接口
	@Resource(name = "com.eorchis.module.interioruser.service.impl.InteriorUserServiceImpl")
	private IInteriorUserService interiorUserService;
	@Autowired
	@Qualifier("attributeConverter")
	private ArrayList<IQueryCommondAttributeConverter> attributeConverter;
	@Autowired
	private ReadExcelUtils excelUtils;
	@Override
	public IBaseService getService() {
		return interiorUserService;
	}

	@Override
	public String getModulePath() {
		return MODULE_PATH;
	}
	
	/**
	 * 修改报名内部学员姓名
	 * @param validCommond
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @createDate 2015-1-4
	 */
	@RequestMapping(value = "/updateInteriorUser")
	public String updateInteriorUser(@ModelAttribute("resultList") InteriorUserValidCommond validCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState)throws Exception{
		validCommond.setUserName(Base64Util.encryptBASE64(validCommond.getUserName()));
		interiorUserService.updateInteriorUser(validCommond);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("操作成功!");
		return "";
	}
	/**
	 *预修改报名内部学员姓名
	 * @param validCommond
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @createDate 2015-1-4
	 */
	@RequestMapping(value = "/preUpdateInteriorUser")
	public String preUpdateInteriorUser(@ModelAttribute("resultList")InteriorUserQueryCommond queryCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState,Model model)throws Exception{
		InteriorUserQueryBean bean=interiorUserService.preUpdateInteriorUser(queryCommond);
		bean.setUserName(Base64Util.toChangeStr(bean.getUserName()));
		model.addAttribute("result", bean);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("查询成功!");
		return "";
	}
	
	/**
	 * 添加内部用户
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年1月7日
	 */
	@RequestMapping(value = "/saveInteriorUser")
	public String saveInteriorUser(@ModelAttribute("result") InteriorUserValidCommond validCommond,
			HttpServletRequest request,HttpServletResponse response, 
			@ModelAttribute("resultState") ResultState resultState)throws Exception {
		if(PropertyUtil.objectNotEmpty(validCommond)){
			String msg=interiorUserService.saveInteriorUser(validCommond);
			if(msg!=null){
				if(msg.equals("报名成功")){
					resultState.setMessage(msg);
					resultState.setState(ResultState.RESULT_STATE_SUCCESS);
				}else{
					resultState.setMessage(msg);
					resultState.setState(ResultState.RESULT_STATE_FAIL);
				}
			}
			
		}
		return "";
	}
	/**
	 * 添加内部用户-单位报名
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-1-9
	 */
	@RequestMapping(value = "/addInteriorUser")
	public String addInteriorUser(@ModelAttribute("result") InteriorUserValidCommond validCommond,
			HttpServletRequest request,HttpServletResponse response, 
			@ModelAttribute("resultState") ResultState resultState)throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);//默认失败
		//获得登陆者的管理范围
		com.eorchis.module.security.cas.domain.Department department=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		if(PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(department.getDeptID())){
			if(PropertyUtil.objectNotEmpty(validCommond.getClassId())){
				//判断传过来的参数
				if(PropertyUtil.objectNotEmpty(validCommond.getLoginId())){
					validCommond.setDeptId(department.getDeptID());
					//validCommond.setDeptId("6680");
					String msg=interiorUserService.addInteriorUser(validCommond);
					if(msg.equals("报名成功")){
						resultState.setMessage(msg);
						resultState.setState(ResultState.RESULT_STATE_SUCCESS);
					}else{
						resultState.setMessage(msg);
						resultState.setState(ResultState.RESULT_STATE_FAIL);
					}			
				}else{
					resultState.setMessage("登录号不能为空！");
				}
			}else{
				resultState.setMessage("没有选中任何班级！");
			}
		}else{
			resultState.setMessage("获取管理范围失败！");
		}
		return "";
	}
	/**
	 * 添加内部用户- Excel导入单位报名
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-1-11
	 */
	@RequestMapping(value = "/importInteriorUser")
	public String importInteriorUser(@ModelAttribute("result") InteriorUserValidCommond validCommond,
			HttpServletRequest request,HttpServletResponse response, 
			@ModelAttribute("resultState") ResultState resultState)throws Exception {
		resultState.setState(ResultState.RESULT_STATE_FAIL);//默认失败
		//获得登陆者的管理范围
		com.eorchis.module.security.cas.domain.Department department=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		if(PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(department.getDeptID())){
				validCommond.setDeptId(department.getDeptID());
				//validCommond.setDeptId("6680");
				String msg="";
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
				for (MultipartFile mf : fileMap.values()) {
					CommonsMultipartFile cmf = (CommonsMultipartFile) mf;
					FileItem file = cmf.getFileItem();
					//File file = new File("D:\\导入单位报名模板.xls");  
					//FileInputStream item = new FileInputStream(file); 
					String name = file.getName();
					//byte[] bytes = null;
					if (name == null || name.trim().equals("")) {
						msg = "您使用的导入模板不正确，请确认后重新导入！";
					} else {
						String fileType = name.substring(name.lastIndexOf("."));
						if (!".xls".equals(fileType)) {
							msg="导入文件格式错误，应为.xls格式，请修改后重新导入。";
						} else {
							byte[] bytes = mf.getBytes();
									
							/*ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
						      byte[] b = new byte[1000];  
						      int n;  
						      while ((n = item.read(b)) != -1) {  
						          bos.write(b, 0, n);  
						      }  
						      item.close();  
						      bos.close();  
						      bytes = bos.toByteArray();*/
						            
							if (bytes.length == 0) {
								msg = "您使用的导入模板不正确，请确认后重新导入！";
							} else {
								//写解析bytes代码
								InputStream in = null;
								ExcelSheet sheet = null;
								in = new ByteArrayInputStream(bytes);
								//读取excel
								sheet=excelUtils.readFile(in);
								if(PropertyUtil.objectNotEmpty(sheet)){
									msg=interiorUserService.importInteriorUser(validCommond, sheet);
								}else {
									msg = "您使用的导入模板不正确，请确认后重新导入！";
								}
							}
						}
					}
				}
				if ("".equals(msg)) {
					resultState.setState(ResultState.RESULT_STATE_SUCCESS);
					resultState.setMessage("导入成功！");
				} else {
					resultState.setMessage(msg);
				}
		}else{
			resultState.setMessage("获取管理范围失败！");
		}
		return "";
	}
	/**
	 * 临时人员列表-单位and工委
	 * @param queryCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-5-6
	 */
	@RequestMapping(value = "/getLUserList")
	public String getLUserList(@ModelAttribute("resultList") InteriorUserQueryCommond queryCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState)
					throws Exception{
		if (attributeConverter != null) {
			parameterValueConver(queryCommond, request, attributeConverter);
		}
		Role role=(Role) request.getSession().getAttribute(SessionConstant.CURRENT_ROLE);
		com.eorchis.module.security.cas.domain.Department department=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		//如果登陆者是单位管理员，需要按照登陆者的管理范围查询人员
		if (PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(role) && role.getRoleCode().equals("department_admin")){
			queryCommond.setSearchTreepath(department.getTreepath());
		}else{
			//工委下正式环境只有两个部门，都需要查询出来
			List<String> depIds=new ArrayList<String>();
			depIds.add("8001");
			depIds.add("8003");
			queryCommond.setSearchDepIds(depIds);
		}
		//queryCommond.setLimit(50);//默认查询50条
		List<QueryClassUserBean> resultList= interiorUserService.getLUserList(queryCommond);
		queryCommond.setResultList(resultList);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("查询成功");	
		return "";
	}
	/**
	 * 用于排序的方法
	 * @param queryCommond
	 * @param request
	 * @param attributeConverter
	 */
	@SuppressWarnings("unchecked")
	private void parameterValueConver(InteriorUserQueryCommond queryCommond,
			HttpServletRequest request,
			List<IQueryCommondAttributeConverter> attributeConverter) {
		for (IQueryCommondAttributeConverter queryCommondAttributeConverter : attributeConverter) {
			queryCommondAttributeConverter.convert(queryCommond,
					request.getParameterMap());
		}
	}
	/**
	 * 修改临时用户
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年5月6日
	 */
	@RequestMapping(value = "/updateLSUser")
	public String updateLSUser(@ModelAttribute("resultList") InteriorUserValidCommond validCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState)throws Exception{
		interiorUserService.updateUser(validCommond);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("操作成功!");
		return "";
	}
	/**
	 * 预更新临时用户
	 * @param queryCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @param model
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年5月6日
	 */
	@RequestMapping(value = "/preUpdateLSUser")
	public String preUpdateLSUser(@ModelAttribute("resultList")InteriorUserQueryCommond queryCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState,Model model)throws Exception{
		model.addAttribute("result", interiorUserService.preUpdateUser(queryCommond));
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("查询成功!");
		return "";
	}
	
	/**
	 *  初始化 对用户名进行加密
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年5月5日
	 */
	@RequestMapping(value = "/encryptionBaseUser")
	public String encryptionBaseUser(@ModelAttribute("resultList") InteriorUserQueryCommond validCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState)throws Exception{
		
		interiorUserService.encryptionBaseUser();
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("操作成功!");
		return "";
	}
	/**
	 * 修改内部用户加密 只使用一次
	 * @param validCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author ShenPS
	 * @date 2015年5月5日
	 */
	@RequestMapping(value = "/encryptionInteriorUser")
	public String encryptionInteriorUser(@ModelAttribute("resultList") InteriorUserQueryCommond validCommond,HttpServletRequest request, 
			HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState)throws Exception{
		
		interiorUserService.encryptionInteriorUser(validCommond);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		resultState.setMessage("操作成功!");
		return "";
	}
	
}
